package com.gy.hsim.bservice.friendInfo.service.impl;

import java.text.SimpleDateFormat;


import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gy.hsim.bservice.framework.bean.BaseReponse;
import com.gy.hsim.bservice.framework.bean.PushMsg;
import com.gy.hsim.bservice.framework.bean.PushMsgBody;
import com.gy.hsim.bservice.framework.bean.PushMsgContent;
import com.gy.hsim.bservice.framework.bean.PushMsgHead;
import com.gy.hsim.bservice.framework.bean.QueryFriendReponse;
import com.gy.hsim.bservice.framework.bean.QueryReponse;
import com.gy.hsim.bservice.framework.bean.QueryVerifyReponse;
import com.gy.hsim.bservice.framework.bean.SystemConfig;
import com.gy.hsim.bservice.framework.common.generator.GuidGenUtil;
import com.gy.hsim.bservice.framework.common.util.HTTPSend;
import com.gy.hsim.bservice.framework.enums.FriendCommandEnum;
import com.gy.hsim.bservice.framework.enums.FriendStatusEnum;
import com.gy.hsim.bservice.framework.enums.MessageResultEnum;
import com.gy.hsim.bservice.framework.mapper.FriendInfoMapper;
import com.gy.hsim.bservice.framework.mq.MQMessageQueue;
import com.gy.hsim.bservice.framework.mq.MQParam;
import com.gy.hsim.bservice.friendInfo.bean.Friend;
import com.gy.hsim.bservice.friendInfo.bean.FriendShield;
import com.gy.hsim.bservice.friendInfo.bean.QueryFriend2UsercData;
import com.gy.hsim.bservice.friendInfo.bean.QueryFriend2UsercReq;
import com.gy.hsim.bservice.friendInfo.bean.QueryFriendReq;
import com.gy.hsim.bservice.friendInfo.bean.QueryFriendResp;
import com.gy.hsim.bservice.friendInfo.service.FriendInfoService;
import com.gy.hsim.bservice.message.bean.Message;
import com.gy.hsxt.uc.search.api.IUCUserInfoSearchService;
import com.gy.hsxt.uc.search.bean.SearchResult;
import com.gy.hsxt.uc.search.bean.SearchUserInfo;

/**
 * @ClassName: FriendInfoServiceImpl
 * @Description: 好友信息业务服务实现类
 * @author Lee
 * @date 2015-1-13 下午5:52:47
 */
@Scope("prototype")
@Service("friendInfoService")
public class FriendInfoServiceImpl implements FriendInfoService {

	private static final Logger log = LoggerFactory
			.getLogger(FriendInfoServiceImpl.class);
	
	@Autowired
	private IUCUserInfoSearchService userInfoSearchService;

	/**
	 * 网元鉴权mapper接口
	 */
	@Autowired
	private FriendInfoMapper friendInfoMapper;

	/**
	 * 配置信息
	 */
	@Autowired
	private SystemConfig config;

	
	

	/**
	 * 获取用户好友备注资料信息
	 * 
	 * @param uid
	 * @return UserInfo
	 * @throws Exception 
	 * @author David 2015-07-13
	 * 
	 */
	@Override
	public List<Friend> queryFriendNickName(QueryFriendReq req,QueryVerifyReponse resp) throws Exception{

		//获取accountID是userID的数据
		List<Friend> friendList = friendInfoMapper.query3(req);
		//获取accountID是friendID的数据
		List<Friend> friendList2 = friendInfoMapper.query31(req);
		
		
		if(friendList != null && friendList.size() > 0) {
			
			if(friendList2 != null && friendList2.size() > 0) {
				
				for (int i = 0 ; i < friendList2.size(); i ++) {
					Friend friend = friendList2.get(i);
					friendList.add(friend);
				}
			}
		} else {
			friendList = friendList2;
		}
		
		int count = friendInfoMapper.queryFriendVerify(req);
		if(count > 0){
			resp.setVerifyFlag("1");
			
		}else{
			
			resp.setVerifyFlag("0");
		}
		
		/**
		 * 如果查不到好友则直接返回查询无数据，不去用户中心查数据
		 */
		if(friendList ==null || friendList.isEmpty()) {
			resp.setRetCode(MessageResultEnum.EXEC_NONEDATA.getRetCode());
			resp.setMessage(MessageResultEnum.EXEC_NONEDATA.getMessage());
			
			return null;
		}
		
		
		
		return friendList;
		
}
	
	/**
	 * 根据用户ID和好友ID，返回是否为好友
	 * 
	 * @param uid
	 * @return UserInfo
	 * @throws Exception 
	 * @author David 2015-07-13
	 * 
	 */
	@Override
	public boolean checkIsUserFriend(QueryFriendReq req, QueryVerifyReponse resp)
			throws Exception {

		int count = friendInfoMapper.query4(req);
		
		if(count >0){
			return true;
		}
		return false;
	}

	
	/**
	 * 获取用户个人资料信息
	 * 
	 * @param uid
	 * @return UserInfo
	 * @throws Exception 
	 */
	@Override
	public List<QueryFriend2UsercData> query(QueryFriendReq req,QueryVerifyReponse resp) throws Exception{
		// TODO Auto-generated method stub

		List<QueryFriend2UsercData> addedFriendList = null;

		String id = req.getAccountId();

		if (id == null || "".equals(id)) {
			return addedFriendList;
		}

		log.info("uid:" + req.getAccountId() + " 查询个人资料 ...");

		log.info("friend_status:" + req.getAccountId() + " 查询个人资料 ...");

		List<Friend> friendList = friendInfoMapper.query1(req);
		
		List<Friend> friendList2 = friendInfoMapper.query2(req);
		if(friendList != null && friendList.size() > 0) {
			if(friendList2 != null && friendList2.size() > 0) {
				for (int i = 0 ; i < friendList2.size(); i ++) {
					Friend friend = friendList2.get(i);
					friendList.add(friend);
				}
			}
		} else {
			friendList = friendList2;
		}
		
		int count = friendInfoMapper.queryFriendVerify(req);
		if(count > 0){
			resp.setVerifyFlag("1");
			
		}else{
			
			resp.setVerifyFlag("0");
		}
		/**
		 * 如果查不到好友则直接返回查询无数据，不去用户中心查数据
		 */
		if(friendList!=null && friendList.isEmpty()) {
			resp.setRetCode(MessageResultEnum.EXEC_NONEDATA.getRetCode());
			resp.setMessage(MessageResultEnum.EXEC_NONEDATA.getMessage());
			
			return null;
		}
				
		/** 好友消息屏蔽map集合 */
		Map<String,String> shieldMap = new ConcurrentHashMap<String,String>();
		/** 好友备注map集合 */
		Map<String,String> nickNameMap = new ConcurrentHashMap<String,String>();
		/** 好友分组map集合 */
		Map<String,String> teamIdMap = new ConcurrentHashMap<String,String>();
		/** 好友分组名称map集合 */
		Map<String,String> teamNameMap = new ConcurrentHashMap<String,String>();
		/** 好友分组备注集合 */
		Map<String,String> teamRemarkMap = new ConcurrentHashMap<String,String>();
		/** 用户昵称集合 */
		Map<String,String> userNicknameMap = new ConcurrentHashMap<String,String>();
		
		if(friendList != null && friendList.size() > 0) {
			for(int i = 0 ; i <friendList.size();i++ ) {
				
				Friend friend = friendList.get(i);
				shieldMap.put(friend.getAccountId(), friend.getIsShield());
				if(null == friend.getNickname() || "".equals(friend.getNickname())){
					nickNameMap.put(friend.getAccountId(), "");
					
				}else{
					nickNameMap.put(friend.getAccountId(), friend.getNickname());
					
				}
				//好友分组ID添加数据
				teamIdMap.put(friend.getAccountId(), friend.getTeamId());  				
				//好友分组名称和好友分组备注添加数据
				if(friend.getTeamId().equals("unteamed")){
					teamNameMap.put(friend.getAccountId(), "");
					teamRemarkMap.put(friend.getAccountId(), "好友未分组");
				}else if(friend.getTeamId().equals("blacklisted")){
					teamNameMap.put(friend.getAccountId(), "黑名单");
					teamRemarkMap.put(friend.getAccountId(), "黑名单组");
				} else{
					teamNameMap.put(friend.getAccountId(), friend.getTeamName());
					teamRemarkMap.put(friend.getAccountId(), friend.getTeamRemark());
				}
				//用户昵称集合设置数据
				if(null == friend.getUserNickname() || "".equals(friend.getUserNickname())){
					userNicknameMap.put(friend.getAccountId(), "");
				} else {
					userNicknameMap.put(friend.getAccountId(), friend.getUserNickname());
				}
				
			}
		}
						
		addedFriendList = getUserList2UserC(friendList);
		
		/** 添加是否屏蔽信息，给移动手机终端使用 */
		if(addedFriendList != null && addedFriendList.size() > 0) {
			for(int i = 0 ; i <addedFriendList.size();i++ ) {
				QueryFriend2UsercData data = addedFriendList.get(i);
				data.setIsShield(shieldMap.get(data.getAccountId()));
				if(null != nickNameMap.get(data.getAccountId()) && !"".equals(nickNameMap.get(data.getAccountId()))){
					data.setNickname(nickNameMap.get(data.getAccountId()));
				}
				data.setRemark(nickNameMap.get(data.getAccountId()));
				data.setTeamId(teamIdMap.get(data.getAccountId()));
				data.setTeamName(teamNameMap.get(data.getAccountId()));
				data.setTeamRemark(teamRemarkMap.get(data.getAccountId()));
				data.setUserNickname(userNicknameMap.get(data.getAccountId()));
			}
		}

		return addedFriendList;
	}

	private List<QueryFriend2UsercData> getUserList2UserC(List<Friend> list) {
		
		List<QueryFriend2UsercData> friendList = null;

		QueryFriend2UsercReq req = new QueryFriend2UsercReq();

		req.setAccessId(config.getAccessID());

		req.setAccessPasswd(config.getAccessPwd());

		req.setFrom(config.getFrom());

		req.setRows(list);
		
		//通过用户中心3.0获取数据
		List<String> idsList = new ArrayList<String>();
		for(Friend friend : list){
			idsList.add(friend.getAccountId().substring(friend.getAccountId().lastIndexOf("_")+1));
		}
		List<SearchUserInfo> searchUserInfoList = userInfoSearchService.getByUserNames(idsList).getList();

		/*HTTPSend send = new HTTPSend();  

		String seqstr = JSON.toJSONString(req);

		String respstr = send.sendRequest(seqstr, config.getUsercUrl());*/
		
		/*log.info("FriendInfoServiceImpl.getUserList2UserC() respstr =  " + respstr);

		QueryFriendResp resp = (QueryFriendResp) JSON.parseObject(respstr,
				QueryFriendResp.class);

		if (resp != null
				&& MessageResultEnum.EXEC_SUCCESS.getRetCode().equals(
						resp.getRetCode())) {
			friendList = resp.getRows();
		}*/
		
		//对列表进行排序
		Collections.sort(list, new Comparator<Friend>() {
            public int compare(Friend arg0, Friend arg1) {
                return String.valueOf(arg0.getFriendStatus()).compareTo(String.valueOf(arg1.getFriendStatus()));
            }
        });	
		List<QueryFriend2UsercData> friendListSort = new ArrayList<QueryFriend2UsercData>();
		//List<SearchUserInfo> SearchUserInfoListSort = new ArrayList<SearchUserInfo>();
		if(searchUserInfoList !=null && searchUserInfoList.size()>0){
			for(Friend friend : list){			
				for(SearchUserInfo SearchUserInfo: searchUserInfoList){
					if(friend.getAccountId().substring(friend.getAccountId().lastIndexOf("_")+1).equals(SearchUserInfo.getCustId()) 
							//|| friend.getFriendId().substring(friend.getFriendId().lastIndexOf("_")+1).equals(SearchUserInfo.getCustId().substring(0, 11))
							|| friend.getAccountId().substring(friend.getAccountId().lastIndexOf("_")+1).equals(SearchUserInfo.getMobile())){
							//|| friend.getFriendId().substring(friend.getFriendId().lastIndexOf("_")+1).equals(SearchUserInfo.getMobile())){
						//SearchUserInfoListSort.add(SearchUserInfo);
						QueryFriend2UsercData QueryFriend2UsercData = new QueryFriend2UsercData();
						QueryFriend2UsercData.setAccountId(friend.getAccountId());
						QueryFriend2UsercData.setHeadPic(String.valueOf(SearchUserInfo.getHeadImage()));
						QueryFriend2UsercData.setNickname(String.valueOf(SearchUserInfo.getNickName()));
						QueryFriend2UsercData.setSign(String.valueOf(SearchUserInfo.getSign()));
						QueryFriend2UsercData.setName(String.valueOf(SearchUserInfo.getName()));
						QueryFriend2UsercData.setMobile(String.valueOf(SearchUserInfo.getMobile()));
						QueryFriend2UsercData.setProvince(String.valueOf(SearchUserInfo.getProvince()));
						QueryFriend2UsercData.setCity(String.valueOf(SearchUserInfo.getCity()));
						QueryFriend2UsercData.setSex(String.valueOf(SearchUserInfo.getSex()));
						QueryFriend2UsercData.setCustId(SearchUserInfo.getCustId());
						QueryFriend2UsercData.setHobby(SearchUserInfo.getHobby());
						friendListSort.add(QueryFriend2UsercData);
					}
				}
			}
		}

		
		return friendListSort;

	}

	/**
	 * 查找是否有id关联的数据
	 * @throws Exception 
	 */
	@Override
	public List<Friend> queryFriendRel(QueryFriendReq req) throws Exception {
		// TODO Auto-generated method stub
		List<Friend> list = friendInfoMapper.queryFriendRel(req);

		return list;
	}

	/**
	 * 添加好友
	 * @throws Exception 
	 */
	@Override
	@Transactional
	public boolean insert(QueryFriendReq data,BaseReponse resp) throws Exception {

		boolean result = false;

		if (data != null) {
			
			if(data.getAccountId()!= null && data.getAccountId().equals(data.getFriendId())) {
				resp.setRetCode(MessageResultEnum.FRIEND_Add_YOURSELF.getRetCode());
				resp.setMessage(MessageResultEnum.FRIEND_Add_YOURSELF.getMessage());
				return false;
			}
			
			int friendStatus = data.getFriendStatus();
			
			/** 如果是好友添加同意、好友添加拒绝、好友删除、好友请求验证调换账号id和好友id */
			if(friendStatus != 1 ) {
				String temp = data.getAccountId();
				data.setAccountId(data.getFriendId());
				data.setFriendId(temp);
			}  
			
			List<Friend> list = queryFriendRel(data);
			
			int count = 0;
					
			if(list != null && list.size() > 0) {
				count = list.size();
				Friend friend = list.get(0);
				if(count > 0 && friend.getFriendStatus() == FriendStatusEnum.FRIEND_ACCEPT_STATUS.getStatusCode() && friendStatus != FriendStatusEnum.FRIEND_DELETE_STATUS.getStatusCode()) {
					resp.setRetCode(MessageResultEnum.FRIEND_IS_IN.getRetCode());
					resp.setMessage(MessageResultEnum.FRIEND_IS_IN.getMessage());
					return false;
				} else if(count > 0 && friend.getFriendStatus() == FriendStatusEnum.FRIEND_ADD_STATUS.getStatusCode() && data.getFriendStatus() == FriendStatusEnum.FRIEND_ADD_STATUS.getStatusCode()) {
					resp.setRetCode(MessageResultEnum.FRIEND_ADD_TWICE.getRetCode());
					resp.setMessage(MessageResultEnum.FRIEND_ADD_TWICE.getMessage());
					return false;
				} else {
					if(data.getAccountId().equals(friend.getFriendId()) && friendStatus == 1) {
						data.setIsFriendAdd(1);
					}
					
					
					if(friendStatus == 4) {
						result = friendInfoMapper.delete(data);
					} else {
						result = friendInfoMapper.update(data);
					}
					
					
				}
			} else {
				data.setSeqId(GuidGenUtil.getLongGuid());

				result = friendInfoMapper.insert(data);
			}
		}

		/** 发送好友状态到业务服务消息队列 */
		sendMsg2Queue(data);

		return result;
	}
    
	private void sendMsg2Queue(QueryFriendReq data) {
		int status = data.getFriendStatus();
		// 如果不是删除好友，需发指令消息
//		if (status != 4) {
		
			PushMsg fre = new PushMsg();
			
			PushMsgHead hd = new PushMsgHead();
			
			PushMsgBody bd = new PushMsgBody();
			
			PushMsgContent content = new PushMsgContent();

			content.setMsg_code("500");
			
			content.setMsg_type("1");

			if (status == FriendStatusEnum.FRIEND_ADD_STATUS.getStatusCode()) {
				content.setFrom(data.getAccountId());
				hd.setSrcUid(data.getAccountId());   //设置消息发送者
				content.setTo(data.getFriendId());
				hd.setDesUids(data.getFriendId());
				
				content.setSub_msg_code(FriendCommandEnum.FRIEND_ADD_COMMAND.getMsgCode());
				content.setMsg_subject(FriendCommandEnum.FRIEND_ADD_COMMAND.getDesc());
				content.setMsg_content(data.getAccountNickname() + config.getFriendAdd());
				content.setMsg_note(data.getAccountNickname());
				content.setMsg_icon(data.getAccountHeadPic());
			} else if (status == FriendStatusEnum.FRIEND_ACCEPT_STATUS.getStatusCode()) {
				content.setFrom(data.getFriendId());
				hd.setSrcUid(data.getFriendId());   //设置消息发送者  
				content.setTo(data.getAccountId());
				hd.setDesUids(data.getAccountId());
				content.setSub_msg_code(FriendCommandEnum.FRIEND_ACCEPT_COMMAND.getMsgCode());
				content.setMsg_subject(FriendCommandEnum.FRIEND_ACCEPT_COMMAND.getDesc());
				content.setMsg_content(data.getAccountNickname() + config.getFriendAccept());
				content.setMsg_note(data.getAccountNickname());
				content.setMsg_icon(data.getAccountHeadPic());
			} else if (status == FriendStatusEnum.FRIEND_REJECT_STATUS.getStatusCode()) {
				content.setFrom(data.getFriendId());
				hd.setSrcUid(data.getFriendId());   //设置消息发送者
				content.setTo(data.getAccountId());
				hd.setDesUids(data.getAccountId());
				content.setSub_msg_code(FriendCommandEnum.FRIEND_REJECT_COMMAND.getMsgCode());
				content.setMsg_subject(FriendCommandEnum.FRIEND_REJECT_COMMAND.getDesc());
				content.setMsg_content(data.getAccountNickname() + config.getFriendReject());
				content.setMsg_note(data.getFriendNickname());
				content.setMsg_icon(data.getFriendHeadPic());
			}else if(status == FriendStatusEnum.FRIEND_DELETE_STATUS.getStatusCode()){
				content.setFrom(data.getFriendId());
				hd.setSrcUid(data.getFriendId());   //设置消息发送者
				content.setTo(data.getAccountId());
				hd.setDesUids(data.getAccountId());
				content.setSub_msg_code(FriendCommandEnum.FRIEND_DELETE_COMMAND.getMsgCode());
				content.setMsg_subject(FriendCommandEnum.FRIEND_DELETE_COMMAND.getDesc());
				content.setMsg_content(data.getAccountNickname() + config.getFriendDelete());
				content.setMsg_note(data.getFriendNickname());
				content.setMsg_icon(data.getFriendHeadPic());
					
			}
			
			content.setMsg_id("");
			
			content.setRes_no("");

			bd.setContent(content);
			
			fre.setHeader(hd);
			
			fre.setBody(bd);
			
			//加好友推送消息发送到 psi网关处理，而不是直接写入 rabbitMQ中
			String freStr = JSON.toJSONString(fre).toString();
			String psiUrl = config.getPsiUrl();  //获取网关地址
			
			HTTPSend send = new HTTPSend();
			send.sendRequest(freStr, psiUrl);  //发送推送消息
			
			/*MQParam mqParam = new MQParam();
			
			mqParam.setRouterKey(config.getBsRouterKeyName());
			
			mqParam.setExchange(config.getBsExchangeName());
			
			mqParam.setChannelCount(config.getBsChannelCount());
			
			mqParam.setQueue(config.getBsQueueName());
			
			mqParam.setChannelCount(config.getBsChannelCount());
			
			MQMessageQueue.instance(mqParam).addEntityQueue(fre);*/
			
			log.info(" FriendInfoServiceImpl.sendMsg2Queue() =  " + JSON.toJSONString(fre));
			log.debug(" FriendInfoServiceImpl.sendMsg2Queue() =  " + JSON.toJSONString(fre));
//			mqSender.send(JSON.toJSONString(fre));


//		}
	}
	

	@Override
	public List<QueryFriend2UsercData> queryWhoAddMeList(QueryFriendReq data,QueryReponse resp) throws Exception {
		// TODO Auto-generated method stub
		List<QueryFriend2UsercData> friendList = null;

		log.info("uid:" + data.getAccountId() + " 查询个人资料 ...");

		log.info("friend_status:" + data.getFriendStatus() + " 查询个人资料 ...");

		List<Friend> list = friendInfoMapper.queryWhoAddMeList(data);
						
		/** 好友消息屏蔽map集合 */
		Map<String,String> friendStatusMap = new ConcurrentHashMap<String,String>();
		
		if(list != null && list.size() > 0) {
			for(int i = 0 ; i <list.size();i++ ) {
				
				Friend friend = list.get(i);
				
				if(friend.getFriendStatus() == FriendStatusEnum.FRIEND_ADD_STATUS.getStatusCode() && (friend.getIsFriendAdd() == 1 && data.getAccountId().equals(friend.getFriendId()) ||  friend.getIsFriendAdd() == 0 && data.getAccountId().equals(friend.getAccountId()))) {
					friend.setFriendStatus(FriendStatusEnum.FRIEND_REQ_CHECK_STATUS.getStatusCode());
				}
				
				if(friend.getAccountId().equals( data.getAccountId())) {
					friend.setAccountId(friend.getFriendId());
				}
				list.set(i, friend);
				
				friendStatusMap.put(friend.getAccountId(), String.valueOf((friend.getFriendStatus())));
			}
		}
		
		
		if(list != null && list.isEmpty()) {
			resp.setRetCode(MessageResultEnum.EXEC_NONEDATA.getRetCode());
			resp.setMessage(MessageResultEnum.EXEC_NONEDATA.getMessage());
			return null;
		}
		
		friendList = getUserList2UserC(list);
		
		/** 添加是否屏蔽信息，给移动手机终端使用 */
		if(friendList != null && friendList.size() > 0) {
			for(int i = 0 ; i <friendList.size();i++ ) {
				QueryFriend2UsercData data2Userc = friendList.get(i);
				data2Userc.setFriendStatus(friendStatusMap.get(data2Userc.getAccountId()));
			}
		}

		return friendList;
	}

	@Override
	public boolean shieldFriendMsg(QueryFriendReq data, BaseReponse resp) throws Exception {
		// TODO Auto-generated method stub

		boolean result = false;

		List<FriendShield> list = friendInfoMapper.queryShieldFriendMsg1(data);

		if (list != null && list.size() > 0) {
			return friendInfoMapper.shieldFriendMsg1(data);
		} else {

			result = friendInfoMapper.shieldFriendMsg2(data);

			if (!result) {
				resp.setRetCode(MessageResultEnum.EXEC_NONEUPDATEDATA
						.getRetCode());
				resp.setMessage(MessageResultEnum.EXEC_NONEUPDATEDATA
						.getMessage());
			}
		}

		return result;
	}
	
	
	@Override
	public boolean updateFriendNickName(QueryFriendReq data, BaseReponse resp) throws Exception {
		// TODO Auto-generated method stub

		boolean result = false;

	    boolean result1 = friendInfoMapper.updateFriendNickName1(data);
	    
	    
	    boolean result2 = friendInfoMapper.updateFriendNickName2(data);

		if(!result1 && !result2){
			resp.setRetCode(MessageResultEnum.EXEC_NONEUPDATEDATA
					.getRetCode());
			resp.setMessage(MessageResultEnum.EXEC_NONEUPDATEDATA
					.getMessage());
		
			
		}else{
			
			result = true;
		}

	

		return result;
	}
	
	
	@Override
	public void queryFriendRemark(QueryFriendReq data, QueryFriendReponse resp) throws Exception {
		// TODO Auto-generated method stub

		//boolean result = false;

		Friend friendInfo  = friendInfoMapper.queryFriendRemark1(data);
		if(null != friendInfo){
			if(null != friendInfo.getNickname() && !"".equals(friendInfo.getNickname())){
				
				resp.setFriendRemark(friendInfo.getNickname());
			}else{
				resp.setFriendRemark("");
			}
			
			
		}else{

			friendInfo  = friendInfoMapper.queryFriendRemark2(data);
			if(null != friendInfo){
				if(null != friendInfo.getNickname() && !"".equals(friendInfo.getNickname())){
						
						resp.setFriendRemark(friendInfo.getNickname());
				}else{
						resp.setFriendRemark("");
				}
				
			}
          
			
		}
	    
		//return result;
	}

	@Override
	public List<FriendShield> queryShieldFriendMsg(QueryFriendReq data,QueryReponse resp) throws Exception {
		// TODO Auto-generated method stub

		List<FriendShield> list = friendInfoMapper.queryShieldFriendMsg1(data);

		if (list != null && list.size() > 0) {
			return list;
		} else {
			list = friendInfoMapper.queryShieldFriendMsg2(data);
		}
		
		if(list != null && list.isEmpty()) {
			resp.setRetCode(MessageResultEnum.EXEC_NONEDATA
					.getRetCode());
			resp.setMessage(MessageResultEnum.EXEC_NONEDATA
					.getMessage());
			return null;
		}

		return list;
	}



	/**
	 * save message
	 */
	public boolean insertMessage(String str) throws Exception {
		boolean result = true;
		try{
			JSONObject json = JSONObject.parseObject(str);
			Message message = new Message();
			String fromUID = json.getString("fromUid");
			String toUID   = json.getString("toUid");
			String mes = json.getString("message");
							
			String mesformat = mes.replaceAll("&quot;","\"");
			JSONObject messageJson = JSONObject.parseObject(mesformat);   
			String msgContent = messageJson.getString("msg_content");  //消息内容从消息体中分离出来
			String msgCode = messageJson.getString("msg_code");        //消息类别代码从消息体中分离出来 
			String dateTime = json.getString("dateTime");
			Date date = new Date(Long.valueOf(dateTime));
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss E");
			message.setFromUid(fromUID);
			message.setToUid(toUID);
			message.setMessage(mes);
			message.setDateTime(df.parse(df.format(date)));
			message.setMessageContent(msgContent);
			message.setMessageCode(msgCode);
			if(message != null){
				result = friendInfoMapper.insertMessage(message);
			}
		}catch(Exception e){			
			e.printStackTrace();
			result = false;
		}
		
		return result;
	}

	@Override
	public boolean insertPushMessage(String str) throws Exception {
		boolean result = true;
		try{
			JSONObject json = JSONObject.parseObject(str);
			Message message = new Message();
			String fromUID = json.getString("fromUid");
			String toUID   = json.getString("toUid");
			String mes = json.getString("message");
							
			String mesformat = mes.replaceAll("&quot;","\"");
			JSONObject messageJson = JSONObject.parseObject(mesformat);   
			String msgContent = messageJson.getString("msg_content");  //消息内容从消息体中分离出来
			String msgCode = messageJson.getString("msg_code"); //消息业务类别大类从消息体中分离出来
			String subMsgCode = messageJson.getString("sub_msg_code"); //消息业务类别子类从消息体中分离出来
			String dateTime = json.getString("dateTime");
			Date date = new Date(Long.valueOf(dateTime));
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss E");
			message.setFromUid(fromUID);
			message.setToUid(toUID);
			message.setMessage(mes);
			message.setDateTime(df.parse(df.format(date)));
			message.setMessageContent(msgContent);
			message.setMessageCode(msgCode);
			message.setSubMessageCode(subMsgCode);
			if(message != null){
				result = friendInfoMapper.insertPushMessage(message);
			}
		}catch(Exception e){			
			e.printStackTrace();
			result = false;
		}
		
		return result;
	}

	@Override
	public boolean insertGroupMessage(String str) throws Exception {
		// TODO Auto-generated method stub
		boolean result = true;
		try{
			JSONObject json = JSONObject.parseObject(str);
			Message message = new Message();
			String fromUID = json.getString("fromUid");
			String toUID   = json.getString("toUid");
			String mes = json.getString("message");
							
			String mesformat = mes.replaceAll("&quot;","\"");
			JSONObject messageJson = JSONObject.parseObject(mesformat);   
			String msgContent = messageJson.getString("msg_content");  //消息内容从消息体中分离出来
			String msgCode = messageJson.getString("msg_code");        //消息类别代码从消息体中分离出来 
			String dateTime = json.getString("dateTime");
			Date date = new Date(Long.valueOf(dateTime));
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss E");
			message.setFromUid(fromUID);
			message.setToUid(toUID);
			message.setMessage(mes);
			message.setDateTime(df.parse(df.format(date)));
			message.setMessageContent(msgContent);
			message.setMessageCode(msgCode);
			if(message != null){
				result = friendInfoMapper.insertGroupMessage(message);
			}
		}catch(Exception e){			
			e.printStackTrace();
			result = false;
		}
		
		return result;
	}

	@Override
	public List<Friend> queryUcRelFriend(String accountId) throws Exception {
		// TODO Auto-generated method stub
		List<Friend> friendList = new ArrayList<Friend>();
		friendList = friendInfoMapper.queryUcRelFriend(accountId);
		return friendList;
	}

}
